package com.zprmb.udzt;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.ll.BaseHelper;
import com.zprmb.udzt.ll.Md5Algorithm;
import com.zprmb.udzt.ll.MobileSecurePayer;
import com.zprmb.udzt.ll.PayOrder;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.MyReceiver;
import com.zprmb.udzt.util.OrderNumUtil;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;

public class V4AddMoneySActiviy extends BaseActivity implements OnClickListener {

	private ImageView iv_v4_addmoney_success_back;
	private TextView tv_v4_addmoney_success_title;
	private TextView tv_addmoney_chongzhi;
	private EditText et_addmoney_jine;
	private int pay_type_flag = 1;// 卡前置
	private String oid_partner;// 商户唯一号
	private String md5_key;// 秘钥
	private String user_name;// 姓名
	private String id_no;// 身份证
	private String card_no;// 银行卡号
	private String bank_name;// 银行名称
	private String notify_url;// 回调地址
	private String user_id;
	private boolean support;
	private String order_no;
	private String strurlencoder;
	private String timeString;
	private double xiane;
	private RelativeLayout rl_back;
	private TextView tv_v4_addmoney_success_xiane;
	private TextView tv_v4_addmoney_success_xiane2;
	private TextView tv_v4_addmoney_success_keyong;
	private ImageView iv_v4_addmoney_success_bankioc;
	private TextView tv_v4_addmoney_success_bankname;
	private TextView tv_v4_addmoney_success_banknum;
	private TextView tv_customer;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.v4_addmoney_success_activity);
		 BbtApplication.getInstance().addActvity(this);
		 IntentFilter mFilter = new IntentFilter();
	        mFilter.addAction("exit1");
	        this.registerReceiver(myReceiver,mFilter);
		if (getShare().getInt("ss", 9527)==9527) {
			Editor editor = getShare().edit();
			editor.putInt("ICBC", R.drawable.bbt_icbc);
			editor.putInt("ABC", R.drawable.bbt_abc);
			editor.putInt("BOC", R.drawable.bbt_boc);
			editor.putInt("CCB", R.drawable.bbt_ccb);
			editor.putInt("CMB", R.drawable.bbt_cbm);
			editor.putInt("CEB", R.drawable.bbt_ceb);
			editor.putInt("SPDB", R.drawable.bbt_spdb);
			editor.putInt("CIB", R.drawable.bbt_cib);
			editor.putInt("PSBC", R.drawable.bbt_psbc);
			editor.putInt("HXB", R.drawable.bbt_hxb); 
			editor.putInt("BCCB", R.drawable.bbt_bccb);
			editor.putInt("BOS", R.drawable.bbt_bos);
			editor.putInt("CGB", R.drawable.bbt_cgb);
			editor.putInt("CMSB", R.drawable.bbt_cmsb);
			editor.putInt("CNCB", R.drawable.bbt_cncb);
			editor.putInt("COMM", R.drawable.bbt_comm);
			editor.putInt("HZCB", R.drawable.bbt_hzcb);
			editor.putInt("NBCB", R.drawable.bbt_nbcb);
			editor.putInt("PAB", R.drawable.bbt_pab);
			editor.putInt("BCCB", R.drawable.bbt_bccb);
			editor.putInt("ss", 1);
			editor.commit();
		}
		initView();
		tv_addmoney_chongzhi.setEnabled(false);
		getBankInfo();
	}
	 MyReceiver myReceiver = new MyReceiver(){
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            finish();
	        }
	    };
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		BbtApplication.getInstance().removeActvity(this);
	}
	private void initView() {
		iv_v4_addmoney_success_back = (ImageView) findViewById(R.id.img_back);
		iv_v4_addmoney_success_back.setOnClickListener(this);
		tv_v4_addmoney_success_title = (TextView) findViewById(R.id.tv_v4_addmoney_success_title);
		tv_v4_addmoney_success_title.getPaint().setFakeBoldText(true);
		tv_v4_addmoney_success_title.setText("充值");
		tv_addmoney_chongzhi = (TextView) findViewById(R.id.tv_addmoney_chongzhi);
		rl_back=(RelativeLayout)findViewById(R.id.rl_back);
		tv_customer=(TextView)findViewById(R.id.enterprise_tel);
		tv_customer.setOnClickListener(this);
		rl_back.setOnClickListener(this);
		tv_addmoney_chongzhi.setOnClickListener(this);
		et_addmoney_jine = (EditText) findViewById(R.id.et_addmoney_jine);
		tv_v4_addmoney_success_xiane = (TextView) findViewById(R.id.tv_v4_addmoney_success_xiane);
		tv_v4_addmoney_success_xiane2 = (TextView) findViewById(R.id.tv_v4_addmoney_success_xiane2);
		iv_v4_addmoney_success_bankioc = (ImageView) findViewById(R.id.iv_v4_addmoney_success_bankioc);
	
		tv_v4_addmoney_success_banknum = (TextView) findViewById(R.id.tv_v4_addmoney_success_banknum);
		
		tv_v4_addmoney_success_keyong = (TextView) findViewById(R.id.tv_v4_addmoney_success_keyong);
	}

	private void getBankInfo() {
		VolleryUtil vollery = new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				Log.e("回调", jsonObject.toString());
				if (jsonObject.optInt("success") == 1) {
					JSONObject json = jsonObject.optJSONObject("data");
					oid_partner = json.optString("oid_partner");
					md5_key = json.optString("md5_key");
					user_name = json.optString("user_name");
					id_no = json.optString("id_no");
					card_no = json.optString("card_no");
					bank_name = json.optString("bank_name");
					notify_url = json.optString("notify_url");
					support = json.optBoolean("support");
					user_id = getShare().getString("userId", "").replace("-", "");					
					tv_v4_addmoney_success_banknum.setText("尾号"+json.optString("card_no").substring(json.optString("card_no").length()-4, json.optString("card_no").length()));
					BbtApplication.getInstance().display("https://rmbboximage.b0.upaiyun.com/bank/"+json.optString("bankNameEn")+".png", iv_v4_addmoney_success_bankioc);
//					iv_v4_addmoney_success_bankioc.setImageResource(getShare().getInt(json.optString("bankNameEn"), 0));
					Log.e("银行", json.optString("bankNameEn"));
					tv_v4_addmoney_success_keyong.setText(json.optString("availableAmount")+"元");
					tv_addmoney_chongzhi.setEnabled(true);
					if (support == false || bank_name.equals("NONSUPPORT")) {
						et_addmoney_jine.setEnabled(false);
						BaseHelper.showDialog(V4AddMoneySActiviy.this,
								"提示", "该账户暂不能充值,请联系客服电话:400-0101-016",
								android.R.drawable.ic_dialog_alert);
					} else {
						et_addmoney_jine.setEnabled(true);
					}
//					getBankMoney(json.optString("bankNameEn"));
					getBankinfo();
				} else {
					Intent intent = new Intent(V4AddMoneySActiviy.this,
							LoginActivity.class);
					startActivity(intent);
				}
			}
			
			

			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};
		vollery.setHeaders("token", getToken());
		vollery.setShow(true);
		vollery.setRequestMethod(0);
		vollery.execute(this, Constant.URL + "mpay/bindingInfo", "");
	}
	private void getBankinfo() {
		// TODO Auto-generated method stub
		VolleryUtil volleryUtil=new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				if(jsonObject.optInt("success")==1){
					Log.e("限额信息", jsonObject.toString());
					JSONObject json = jsonObject.optJSONObject("data");
					tv_v4_addmoney_success_xiane.setText(json.optString("tips"));
					
					xiane=json.optInt("single");
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};
		volleryUtil.setRequestMethod(0);
		volleryUtil.setHeaders("token", getToken());
		volleryUtil.setHeaders("client", "android");
		volleryUtil.execute(V4AddMoneySActiviy.this, Constant.URL+"/api/v5/user/self", "");
	}
	protected void onRestart() {
		super.onRestart();
		getBankInfo();
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_back:
			finish();
			break;
		case R.id.rl_back:
			finish();
			break;
		case R.id.tv_addmoney_chongzhi:
			if (support == false || bank_name.equals("NONSUPPORT")) {
				BaseHelper.showDialog(V4AddMoneySActiviy.this, "提示",
						"该账户暂不能充值,请联系客服电话:400-0101-016",
						android.R.drawable.ic_dialog_alert);
				return;
			}
			if (et_addmoney_jine.getText().toString().equals("")) {
				ToastUtil.showToast(this, "请输入正确的金额");
				return;
			}
			if(Double.parseDouble(et_addmoney_jine.getText().toString())>xiane){
				ToastUtil.showToast(this, "充值金额大于单笔金额");
				return;
			}
			if(Double.parseDouble(et_addmoney_jine.getText().toString())<1){
				ToastUtil.showToast(this, "充值金额不能小于1元");
				return;
			}
			/*
			 * if (Integer.valueOf(et_addmoney_jine.getText().toString())<1) {
			 * ToastUtil.showToast(this, "充值金额不能小于1元"); return; }
			 */
			timeString = getTime();
			order_no = getOrder_no();
			tv_addmoney_chongzhi.setEnabled(false);
			upSevice();
			break;


		case R.id.enterprise_tel:
			BaseHelper.showDialog2(this, "拨号", "400-0101-016", 1);
			break;
		}
	}

	private Handler mHandler = createHandler();

	private Handler createHandler() {
		return new Handler() {
			public void handleMessage(Message msg) {
				String strRet = (String) msg.obj;
				switch (msg.what) {
				case Constant.RQF_PAY: {
					JSONObject objContent = BaseHelper.string2JSON(strRet);
					String retCode = objContent.optString("ret_code");
					String retMsg = objContent.optString("ret_msg");
					// 成功
					if (Constant.RET_CODE_SUCCESS.equals(retCode)) {
						// TODO 卡前置模式返回的银行卡绑定协议号，用来下次交易时使用，此处仅作为示例使用。正式接入时去掉
						if (pay_type_flag == 1) {
							// agree_no = objContent.optString("agreementno",
							// "");
						}
						// BaseHelper.showDialog(AddMoneyActivity.this,
						// "提示","交易成功，交易状态码：" +
						// retCode,android.R.drawable.ic_dialog_alert);
//						BaseHelper.showDialog(V4AddMoneySActiviy.this, "提示",
//								"交易成功", android.R.drawable.ic_dialog_alert);
						Intent intent=new Intent(V4AddMoneySActiviy.this,Addmoney.class);
						intent.putExtra("money", et_addmoney_jine.getText().toString());
						startActivity(intent);
						tv_addmoney_chongzhi.setEnabled(true);
					} else if (Constant.RET_CODE_PROCESS.equals(retCode)) {
						// TODO 处理中，掉单的情形
//						String resulPay = objContent.optString("result_pay");
//						if (Constant.RESULT_PAY_PROCESSING
//								.equalsIgnoreCase(resulPay)) {
////							BaseHelper.showDialog(V4AddMoneySActiviy.this,
////									"提示", objContent.optString("ret_msg")
////											+ "交易状态码：" + retCode,
////									android.R.drawable.ic_dialog_alert);
//							Toast.makeText(V4AddMoneySActiviy.this, "提示"+objContent.optString("ret_msg")
//									+ "交易状态码：" + retCode, 2000).show();
//							// BaseHelper.showDialog(AddMoneyActivity.this,
//							// "提示",objContent.optString("ret_msg"),android.R.drawable.ic_dialog_alert);
//						}
					} else {
						// TODO 失败
//						BaseHelper.showDialog(V4AddMoneySActiviy.this, "提示",
//								retMsg + "，交易状态码:" + retCode,
//								android.R.drawable.ic_dialog_alert);
						Intent intent=new Intent(V4AddMoneySActiviy.this,Addmoneyfail.class);
						intent.putExtra("money", et_addmoney_jine.getText().toString());
						startActivity(intent);
						tv_addmoney_chongzhi.setEnabled(true);
					}
				}
					break;
				}
				super.handleMessage(msg);
			}
		};
	}
	
//	private void getBankMoney(String bankName){
//		AjaxParams params = new AjaxParams();
//		params.put("bankName", bankName);
//		VolleryUtil vollery = new VolleryUtil() {
//			
//			@Override
//			public void onUpDate(JSONObject jsonObject) {
//				// TODO Auto-generated method stub
//				Log.e("限额数据", jsonObject.toString());
//				if (jsonObject.optInt("success")==1) {
//					JSONObject json = jsonObject.optJSONObject("data");
//					if (json.optString("limitByDay").equals("null")) {
//						tv_v4_addmoney_success_xiane.setText((json.optDouble("limitByOnce")/10000)+"万元");
//						tv_v4_addmoney_success_xiane2.setText("不限");
//					    xiane=json.optDouble("limitByOnce");
//					}else {
//						tv_v4_addmoney_success_xiane.setText((json.optDouble("limitByOnce")/10000)+"万元");
//						tv_v4_addmoney_success_xiane2.setText((json.optDouble("limitByDay")/10000)+"万元");
//					}
//					 xiane=json.optInt("limitByOnce");
//				}
//			}
//			
//			@Override
//			public void onError() {
//				// TODO Auto-generated method stub
//				
//			}
//		};
//		vollery.setHeaders("token", getToken());
//		vollery.setHeaders("client", "android");
//		vollery.setRequestMethod(0);
//		vollery.execute(this, Constant.URL+"api/v2/getLLSupportBankLimit?", params.toString());
//	}
	
	private PayOrder constructPreCardPayOrder() {
		// SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		// Date date = new Date();
		// String timeString = dataFormat.format(date);
		// date.getTime();
		PayOrder order = new PayOrder();
		order.setBusi_partner("101001");
		order.setNo_order(order_no);
		order.setDt_order(timeString);
		// System.out.println("timeString="+timeString);
		order.setName_goods("投资");
		order.setNotify_url(notify_url);
		order.setSign_type("MD5");
		order.setValid_order("100");
		order.setUser_id(user_id); 
		order.setId_no(id_no);// 身份证
		order.setAcct_name(user_name);// 姓名
		order.setMoney_order(et_addmoney_jine.getText().toString());// 金额
		// order.setId_type("0");
		// 银行卡卡号，该卡首次交易时必填
		order.setCard_no(card_no);// 银行卡
		// 银行卡历次交易时填写，可以查询得到，协议号匹配会进入SDK，
		// order.setNo_agree(agree_no);
		// order.setFlag_modify("1");//不可修改
		// 风险控制参数
		order.setRisk_item(constructRiskItem(timeString, user_name, id_no,
				user_id));
		// TODO 商户号
		order.setOid_partner(oid_partner);
		String content = BaseHelper.sortParam(order);
		// TODO MD5 签名方式, 签名方式包括两种，一种是MD5，一种是RSA 这个在商户站管理里有对验签方式和签名Key的配置。
		String sign = Md5Algorithm.getInstance().sign(content, md5_key);
		order.setPay_type("2");// 交易方式(2:借记卡,3:信用卡)
		order.setSign(sign);
		return order;
	}

	/**
	 * 风险控制
	 * @return
	 */
	private static String constructRiskItem(String timeString,
			String user_name, String id_no, String user_id) {
		JSONObject mRiskItem = new JSONObject();
		try {
			// 绑定手机号
			// mRiskItem.put("user_info_bind_phone", "18612205548");
			// mRiskItem.put("user_info_dt_register", "201407251110120");
			// mRiskItem.put("request_imei", "1122111221");

			mRiskItem.put("frms_ware_category", "2009");

			mRiskItem.put("user_info_identify_type", "3");

			mRiskItem.put("user_info_identify_state", "1");

			mRiskItem.put("user_info_id_no", id_no);

			mRiskItem.put("user_info_full_name", user_name);

			mRiskItem.put("user_info_dt_register", timeString);

			mRiskItem.put("user_info_mercht_userno", user_id);

			// 用户在商户系统中的登陆名（手机号、邮箱等标识）
			// mRiskItem.put("user_info_mercht_userlogin", value);

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return mRiskItem.toString();
	}

	private void upSevice() {
		try {
			strurlencoder = URLEncoder.encode(user_name, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		AjaxParams params = new AjaxParams();
		params.put("orderId", order_no);
		params.put("userId", user_id);
		params.put("cardNo", card_no);
		params.put("amount", et_addmoney_jine.getText().toString());
		params.put("name", strurlencoder);
		params.put("payType", "LL_PAY");
		params.put("timestamp", timeString);
		VolleryUtil vollery = new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				Log.e("充值", jsonObject.toString());
				// TODO Auto-generated method stub
				// System.out.println("addmoney==="+getJson());
				if (jsonObject.optInt("success") == 1) {
					
					PayOrder order = null;
					order = constructPreCardPayOrder();
					String content4Pay = BaseHelper.toJSONString(order);
					// 关键 content4Pay
					// 用于提交到交易SDK的订单交易串，如遇到签名错误的情况，请将该信息帖给我们的技术支持
					// Log.i(AddMoneyActivity.class.getSimpleName(),
					// content4Pay);
					MobileSecurePayer msp = new MobileSecurePayer();
					msp.payAuth(content4Pay, mHandler, Constant.RQF_PAY,
							V4AddMoneySActiviy.this, false);
					// Log.i(AddMoneyActivity.class.getSimpleName(),
					// String.valueOf(bRet));
					
				} else {
					if (jsonObject.optString("comment").equals("please login")) {
						Intent intent = new Intent(V4AddMoneySActiviy.this,LoginActivity.class);
						startActivity(intent);
					}else{
						ToastUtil.showCenterToast(V4AddMoneySActiviy.this, jsonObject.optString("comment"));
					}
				 	
					
					tv_addmoney_chongzhi.setEnabled(true);
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				tv_addmoney_chongzhi.setEnabled(true);
			}
		};
		vollery.setHeaders("token", getToken());
		vollery.setShow(true);
		vollery.execute(this, Constant.URL + "/mpay/authpay" +
				"?",
				params.toString());
	}

//	private String getTime() {
//		SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//		Date date = new Date();
//		String timeString = dataFormat.format(date);
//		return timeString;
//	}

	private String getOrder_no() {
		String orderno = OrderNumUtil.GenerateRandomNumber(20);
		return orderno;
	}
	
	private void orderNoFromBackground(){
		
		VolleryUtil vollery = new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};
		
		
		vollery.execute(this, Constant.URL+"", "");
		
	}
	
	
	

}
